

export class FBindFunction {

    protected funcList: { func: Function, target: any, id: Function }[] = []


    private getIndex(func: Function, target: any) {
        for (let index = 0; index < this.funcList.length; index++) {
            const element = this.funcList[index];
            if (element.func == func && element.target == target) {
                return index
            }
        }
        return -1;
    }

    onFunc(callFunc: Function, func: Function, target: any) {
        let id = this.getFunc(func, target)
        callFunc(id)
    }

    offFunc(callFunc: Function, func: Function, target: any): void {
        let index = this.getIndex(func, target)
        if (index >= 0) {
            let param = this.funcList[index]
            callFunc(param.id);
        }
    }

    //没有删除是在重复利用，但是要确保对象在销毁后不再使用
    getFunc(func: Function, target: any) {
        let index = this.getIndex(func, target)
        if (index >= 0) {
            let param = this.funcList[index]
            return param.id;
        } else {
            let id = func.bind(target)
            this.funcList.push({ func: func, target: target, id: id })
            return id;
        }
    }

    clear() {
        this.funcList = []
    }
}